﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Bricks.Business.Service.Impl;
using Bricks.Site.Models;
using Bricks.Business.Models.FlowProcess;
using System.Xml;
using System.Web.Script.Serialization;
using Bricks.Business.Service;
using Bricks.Component.Utils;
using Bricks.Site.Web.CommonUtils;
using Bricks.Component.Utils.Extensions;
using Bricks.Business.Models.ProjectContract;
using Bricks.Business.Service.CommonSupport;
using Bricks.Site.Models.DBViewModel.Project;
using Bricks.Component.Data;
using Bricks.Site.Models.DBViewModel.Contract;
using Bricks.Business.Models.Account;
using System.Configuration;
using Bricks.Site.Models.ProjectContract;

namespace Bricks.Site.Web.Controllers
{
    /// <summary>
    /// 项目管理（在建项目概况，完工项目概况）
    /// </summary>
    [Export]
    public class ProjectInfoController : BaseController
    {
        [Import]
        public IProjectInfoService ProjectInfoService { get; set; }
        [Import]
        public IFinishedProjectInfoService FinishedProjectInfoService { get; set; }
        [Import]
        public IUserOrgService UserOrgService { get; set; }
        [Import]
        public IOrgInfoService OrgInfoService { get; set; }
        [Import]
        public IDocumentService DocumentService { get; set; }

        #region 获取项目列表
        public ActionResult ProjectInfoList()
        {
            return Json(ProjectInfoService.GetProjectInfoList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult ProjectInfoListForFlow()
        {
            List<ProjectInfoView> lstProjectInfoView = ProjectInfoService.GetProjectInfoList();
            GetProjectInfoListForPreview(ref lstProjectInfoView);
            return Json(lstProjectInfoView, JsonRequestBehavior.AllowGet);
        }

        private void GetProjectInfoListForPreview(ref List<ProjectInfoView> lstProjectInfoView)
        {
            //如果当前用户不是超级管理员且不在能查看合同的部门列表里面，则需要对登陆用户的有流程的单据列表进行筛选：获取需要做合同筛选的顶级部门，只能查看登陆用户所属部门或者子部门与客户端合同对应单位相同的那些

            //获取登陆用户的机构信息
            List<OrgInfo> orgs = (from u in UserInfoService.Users
                                  join uo in UserOrgService.UserOrgs on u.ID equals uo.UserID
                                  join o in OrgInfoService.Orgs on uo.OrgID equals o.ID
                                  where u.UserName == User.Identity.Name
                                  select o).ToList();
            if (orgs.Count() > 0 && SystemData.Instance.CurrentUser.UserType == UserType.Common && !FlowFilterAndRequestUtils.IsContainLoginOrg(orgs))
            {
                string topDepartmentOfNeedFilterContractStr = ConfigurationManager.AppSettings["TopDepartmentOfNeedFilterContract"] as string;
                if (!string.IsNullOrEmpty(topDepartmentOfNeedFilterContractStr))
                {
                    //获取能新增客户端合同的所有部门
                    List<Guid> lstAllAddConstructionContractDepartment = new List<Guid>();
                    string[] addConstructionContractTopDepartmentArr = topDepartmentOfNeedFilterContractStr.Split(',');
                    foreach (string addConstructionContractTopDepartment in addConstructionContractTopDepartmentArr)
                    {
                        OrgInfo orgInfo = OrgInfoService.Orgs.SingleOrDefault(o => o.OrgCode == addConstructionContractTopDepartment);
                        if (orgInfo != null)
                        {
                            lstAllAddConstructionContractDepartment.Add(orgInfo.ID);
                            FlowFilterAndRequestUtils.GetSubOrgInfo(orgInfo.ID, ref lstAllAddConstructionContractDepartment);
                        }
                    }

                    //如果所有能新增客户端合同的机构包含登陆用户所在部门，则需要筛选数据
                    if (FlowFilterAndRequestUtils.IsContainLoginOrg(lstAllAddConstructionContractDepartment, orgs))
                    {
                        string correspondenceUnitStr = string.Empty;
                        foreach (var org in orgs)
                        {
                            correspondenceUnitStr += "'" + org.ID + "',";
                            FlowFilterAndRequestUtils.GetSubCorrespondenceUnit(org.ID, ref correspondenceUnitStr);
                        }
                        string sql = "select * from V_ContractInfoes where CorrespondenceUnit in (" + correspondenceUnitStr.Trim(',') + ")";
                        var lstContractInfo = DbSqlHelper<VMContractInfo>.SqlQueryCommon(sql);

                        lstProjectInfoView = (from p in lstProjectInfoView
                                              join c in lstContractInfo
                                              on p.ID equals c.PID
                                              select p).DistinctBy(p => p.ID).OrderBy(p => p.OrderNo).ToList();
                    }
                }
            }
        }
        #endregion

        #region 在建项目概况
        public ActionResult Index()
        {
            ViewBag.ToolBarInfo = base.GetToolBarInfo();
            return View();
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDataList()
        {
            var queryData = ProjectInfoService.ProjectInfoes.OrderBy(m => m.OrderNo).ToList();
            var list = from m in queryData
                       select new
                       {
                           ID = m.ID,
                           ProjectCode = m.ProjectCode,
                           ProjectName = m.ProjectName,
                           Description = m.Description,
                           OrderNo = m.OrderNo,
                           IsDeleted = m.IsDeleted,
                           AddDate = m.AddDate,
                           RegisterUserID = m.RegisterUserID,
                           RegisterUser = UserInfoService.GetUserNameByID(m.RegisterUserID),
                           RegisterDate = m.RegisterDate,
                           BuildType = m.BuildType,
                           InvestType = m.InvestType,
                           BuildContent = m.BuildContent,
                           Attachment = m.Attachment
                       };
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {
            Guid guidID = id.ToGuid();
            var exeResult = ProjectInfoService.Delete(guidID);
            if (exeResult.ResultType == OperationResultType.Success)
            {
                var docDeleteResult = DocumentService.DeleteByInstanceID(guidID);
                if (docDeleteResult == true)
                {
                    exeResult.Message += "，已删除关联附件记录";
                }
            }
            return Json(exeResult);
        }

        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(string id)
        {
            //ProjectInfo model = new ProjectInfo();
            ////如果是编辑
            //if (!String.IsNullOrEmpty(id))
            //{
            //    Guid guidID = id.ToGuid();
            //    var record = ProjectInfoService.ProjectInfoes.FirstOrDefault(m => m.ID == guidID);
            //    if (record != null)
            //    {
            //        model = record;
            //        ViewBag.RegisterUser = UserInfoService.GetUserInfoByID(model.RegisterUserID).UserName;
            //    }
            //}
            //else
            //{
            //    ViewBag.RegisterUser = SystemData.Instance.CurrentUser.UserName;
            //    //model.RegisterUser = SystemData.Instance.CurrentUser.UserName;
            //    model.RegisterUserID = SystemData.Instance.CurrentUser.ID;
            //    model.RegisterDate = DateTime.Now.ToString("yyyy-MM-dd");  //默认当天
            //}
            VMProjectInfo model = new VMProjectInfo();
            if (!String.IsNullOrEmpty(id))
            {
                string sql = "select * from V_ProjectInfoes where ID='" + id + "'";
                var listView = DbSqlHelper<VMProjectInfo>.SqlQueryCommon(sql);
                if (listView != null && listView.Count == 1)
                {
                    model = listView[0];
                    ViewBag.RegisterUser = UserInfoService.GetUserInfoByID(model.RegisterUserID).UserName;
                    if (!string.IsNullOrEmpty(model.BuildUnit as string) || model.ScheduledStartDate != null
                        || model.ScheduledEndDate != null || model.Period != null || model.ScheduledInvestment != null
                        || !string.IsNullOrEmpty(model.StartStake as string) || !string.IsNullOrEmpty(model.EndStake as string)
                        || !string.IsNullOrEmpty(model.ProjectOverview as string))
                    {
                        if (model.ScheduledStartDate != null)
                        {
                            model.ScheduledStartDateStr = Convert.ToDateTime(model.ScheduledStartDate).ToString("yyyy-MM-dd");
                        }
                        if (model.ScheduledEndDate != null)
                        {
                            model.ScheduledEndDateStr = Convert.ToDateTime(model.ScheduledEndDate).ToString("yyyy-MM-dd");
                        }
                        model.IsShowExtInfo = "1";
                    }
                    else
                    {
                        model.IsShowExtInfo = "0";
                    }
                }
            }
            else
            {
                ViewBag.RegisterUser = SystemData.Instance.CurrentUser.UserName;
                //model.RegisterUser = SystemData.Instance.CurrentUser.UserName;
                model.ID = Guid.NewGuid();
                model.RegisterUserID = SystemData.Instance.CurrentUser.ID;
                model.RegisterDate = DateTime.Now.ToString("yyyy-MM-dd");  //默认当天
                model.IsShowExtInfo = "0";
            }
            return View(model);
        }

        /// <summary>
        /// 新增或编辑（响应）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]  //添加这个是为了防止错误：从客户端中检测到有潜在危险的 Request.Form 值
        public ActionResult EditPost(VMProjectInfo model)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            ProjectInfo record = ProjectInfoService.ProjectInfoes.FirstOrDefault(m => m.ID == model.ID);

            //新增
            if (record == null)
            {
                record = new ProjectInfo();
                record.ID = model.ID;
                record.ProjectCode = model.ProjectCode;
                record.ProjectName = model.ProjectName;
                record.RegisterUserID = model.RegisterUserID;
                record.RegisterDate = model.RegisterDate;
                record.BuildType = model.BuildType;
                record.InvestType = model.InvestType;
                record.BuildContent = model.BuildContent;
                record.Description = model.Description;
                record.Attachment = model.Attachment;
                record.UpdateTime = DateTime.Now;

                result = ProjectInfoService.Add(record);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //修改
            else
            {
                record.ProjectCode = model.ProjectCode;
                record.ProjectName = model.ProjectName;
                record.RegisterUserID = model.RegisterUserID;
                record.RegisterDate = model.RegisterDate;
                record.BuildType = model.BuildType;
                record.InvestType = model.InvestType;
                record.BuildContent = model.BuildContent;
                record.Description = model.Description;
                record.Attachment = model.Attachment;
                record.UpdateTime = DateTime.Now;
                result = ProjectInfoService.Modify(record);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //return View();
            return Json(result, "text/html");
        }

        /// <summary>
        /// 排序设置
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="order">排序</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetOrder(string id, string order)
        {
            Guid guidID = id.ToGuid();
            var exeResult = ProjectInfoService.SetOrder(guidID, order);
            return Json(exeResult);
        }

        /// <summary>
        /// 设置禁用或启用
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="isEnable">是否启用</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetEnable(string id, string isEnable)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            Guid guidID = id.ToGuid();
            var record = ProjectInfoService.ProjectInfoes.FirstOrDefault(m => m.ID == guidID);
            if (record != null)
            {
                record.IsDeleted = isEnable == "False";
                //UserView view = new UserView();
                //view = record.CopyTo<UserView>();
                result = ProjectInfoService.Modify(record);
                if (result.ResultType == OperationResultType.Success)
                    result.Message = (isEnable == "True" ? "启用" : "禁用") + "成功";
            }
            return Json(result);
            //return View();
        }

        /// <summary>
        /// 预览
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Preview(string id)
        {
            //ProjectInfo model = new ProjectInfo();
            ////如果是编辑
            //if (!String.IsNullOrEmpty(id))
            //{
            //    Guid guidID = id.ToGuid();
            //    var record = ProjectInfoService.ProjectInfoes.FirstOrDefault(m => m.ID == guidID);
            //    if (record != null)
            //    {
            //        model = record;
            //        ViewBag.RegisterUser = UserInfoService.GetUserInfoByID(model.RegisterUserID).UserName;
            //    }
            //}
            VMProjectInfo model = new VMProjectInfo();
            model.IsShowExtInfo = "0";
            if (!String.IsNullOrEmpty(id))
            {
                string sql = "select * from V_ProjectInfoes where ID='" + id + "'";
                var listView = DbSqlHelper<VMProjectInfo>.SqlQueryCommon(sql);
                if (listView != null && listView.Count == 1)
                {
                    model = listView[0];
                    ViewBag.RegisterUser = UserInfoService.GetUserInfoByID(model.RegisterUserID).UserName;
                    if (!string.IsNullOrEmpty(model.BuildUnit as string) || model.ScheduledStartDate != null
                        || model.ScheduledEndDate != null || model.Period != null || model.ScheduledInvestment != null
                        || !string.IsNullOrEmpty(model.StartStake as string) || !string.IsNullOrEmpty(model.EndStake as string)
                        || !string.IsNullOrEmpty(model.ProjectOverview as string))
                    {
                        if (model.ScheduledStartDate != null)
                        {
                            model.ScheduledStartDateStr = Convert.ToDateTime(model.ScheduledStartDate).ToString("yyyy-MM-dd");
                        }
                        if (model.ScheduledEndDate != null)
                        {
                            model.ScheduledEndDateStr = Convert.ToDateTime(model.ScheduledEndDate).ToString("yyyy-MM-dd");
                        }
                        model.IsShowExtInfo = "1";
                    }
                    else
                    {
                        model.IsShowExtInfo = "0";
                    }
                }
            }
            return View(model);
        }
        #endregion

        #region 完工项目概况
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public ActionResult FinishedIndex()
        {
            ViewBag.ToolBarInfo = base.GetToolBarInfo();
            return View();
        }

        /// <summary>
        /// 获取列表数据(完工项目概况)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetFinishedDataList()
        {
            var queryData = FinishedProjectInfoService.FinishedProjectInfoes.ToList();
            var list = from m in queryData
                       select new FinishedProjectInfoView
                       {
                           ID = m.ID,
                           ProjectName = m.ProjectName,
                           FinishTime = m.FinishTime,
                           PlanAccount = m.PlanAccount,
                           FinalAccount = m.FinalAccount,
                           OfficialNum = m.OfficialNum,
                           OfficialTime = m.OfficialTime,
                           Attachment = m.Attachment,
                           RegisterUserID = m.RegisterUserID,
                           RegisterDepartmentAndUser = UserInfoService.GetUserOrgAndName(m.RegisterUserID),
                           LoginUserID = SystemData.Instance.CurrentUser.ID
                       };
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FinishedEdit(string id)
        {
            FinishedProjectInfoView viewModel = new FinishedProjectInfoView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = FinishedProjectInfoService.FinishedProjectInfoes.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    viewModel = record.CopyTo<FinishedProjectInfoView>();
                    viewModel.RegisterDepartmentAndUser = UserInfoService.GetUserOrgAndName(viewModel.RegisterUserID);
                }
            }
            //如果是新增
            else
            {
                viewModel.RegisterUserID = SystemData.Instance.CurrentUser.ID;
                viewModel.RegisterDepartmentAndUser = UserInfoService.GetUserOrgAndName(SystemData.Instance.CurrentUser.ID);
            }
            return View(viewModel);
        }

        /// <summary>
        /// 新增或编辑（响应）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]  //添加这个是为了防止错误：从客户端中检测到有潜在危险的 Request.Form 值
        public ActionResult FinishedEditPost(FinishedProjectInfoView model)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            FinishedProjectInfo record = FinishedProjectInfoService.FinishedProjectInfoes.FirstOrDefault(m => m.ID == model.ID);

            //新增
            if (record == null)
            {
                result = FinishedProjectInfoService.Add(model);
            }
            //修改
            else
            {
                result = FinishedProjectInfoService.Modify(model);
            }
            return Json(result, "text/html");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FinishedDelete(string id)
        {
            Guid guidID = id.ToGuid();
            var exeResult = FinishedProjectInfoService.Delete(guidID);
            if (exeResult.ResultType == OperationResultType.Success)
            {
                var docDeleteResult = DocumentService.DeleteByInstanceID(guidID);
                if (docDeleteResult == true)
                {
                    exeResult.Message += "，已删除关联附件记录";
                }
            }
            return Json(exeResult);
        }

        /// <summary>
        /// 预览
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FinishedPreview(string id)
        {
            FinishedProjectInfoView viewModel = new FinishedProjectInfoView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = FinishedProjectInfoService.FinishedProjectInfoes.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    viewModel = record.CopyTo<FinishedProjectInfoView>();
                    viewModel.RegisterDepartmentAndUser = UserInfoService.GetUserOrgAndName(viewModel.RegisterUserID);
                }
            }
            return View(viewModel);
        }
        #endregion
    }
}